import { updatePwd, editUser, delUser, resetUser } from '@/api/user'
import { getBusInfo, editBus, userEnable } from '@/api/firmMg'

const getDefaultState = () => {
  return {
    conditions: {},
    firmInfo: {}
  }
}

const state = getDefaultState()

const getters = {
  tenantId: (state, getters, rootState) => rootState.user.tenantId
}

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  UPDATE_CONDITIONS: (state, payload) => {
    const { conditions } = state
    state.conditions = payload ? { ...conditions, ...payload } : {}
  }
}

const actions = {
  // 修改密码
  async onUpdatePwd({ commit }, payload) {
    await updatePwd(payload)
  },
  // 获取企业详情
  async getBusInfo({ state, getters }) {
    const { retData } = await getBusInfo(getters.tenantId)
    state.firmInfo = retData || {}
    return retData
  },
  // 修改企业信息
  async editBus({ getters }, payload) {
    payload.id = getters.tenantId
    const { retData } = await editBus(payload)
    return retData
  },
  // 编辑用户
  async onEditUser({ dispatch, commit }, payload = {}) {
    const { success } = await editUser(payload)
    if (success) {
      dispatch('hideModal', {}, { root: true })
      commit('UPDATE_CONDITIONS')
    }
  },

  // 删除用户
  async onDelUser({ dispatch, commit }, id) {
    const { success } = await delUser(id)
    if (success) {
      dispatch('hideModal', {}, { root: true })
      commit('UPDATE_CONDITIONS')
    }
  },
  // 重置 用户
  async onResetUser({ dispatch, commit }, id) {
    const { success } = await resetUser(id)
    if (success) {
      dispatch('hideModal', {}, { root: true })
      commit('UPDATE_CONDITIONS')
    }
  },
  // Status
  async userEnableStatus({ dispatch, commit }, payload = {}) {
    const { success } = await userEnable(payload)
    if (success) {
      commit('UPDATE_CONDITIONS')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
